package useless;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;

/**
 * Created by tiang on 2018/7/12.
 */
public class RandomList {
    static class RandomRelease{
        // 释放的时间列表
        private ArrayList<Integer> times = new ArrayList<>();
        // 释放的时间
        private Set<Integer> releaseTime = new HashSet<>();
        // 满足的期望值
        private double expect;
        // 浮动范围
        private double deviation;
        public RandomRelease(double ex, double de){
            expect = ex;
            deviation = de;
        }
        public void addTime(int time){
            times.add(time);
        }

        public void generateRandomList() {
            // 首先根据期望值及其浮动范围，计算这次的随机生成的释放时间个数
            double low = times.size() * (expect - deviation),
                    high = times.size() * (expect + deviation);
            // 本次释放的个数，随机在一个区间之内
            int releaseNum = (int)Math.round(Math.random()*(high-low)+low);
            // 判断释放个数是否为0
            releaseNum = releaseNum <= 0 ? 0 : releaseNum;
            if (releaseNum == 0)
                return;
            // 判断释放个数是否超过上限
            releaseNum = releaseNum >= times.size() ? times.size() : releaseNum;
            if (releaseNum == times.size())
                for (int i = 0; i < times.size(); i++)
                    releaseTime.add(times.get(i));

            System.out.println("时间数"+releaseNum);
            int tryThreshold = 10;
            int i = 0, tryTimes = 0;
            while(releaseTime.size()<releaseNum){
                int pos = (int)(Math.random()*times.size());
                System.out.println("pos:"+pos);
                if(tryTimes<tryThreshold) {
                    if (Math.random() <= 0.5)
                        releaseTime.add(times.get(pos));
                    i++;
                    if (i >= times.size()) {
                        tryTimes++;
                        i = 0;
                    }
                }else{
                    releaseTime.add(times.get(pos));
                    i++;
                }
            }
            System.out.println("尝试次数："+tryTimes);
            for(int t : releaseTime){
                System.out.println(t);
            }
        }

        public boolean releaseOrNot(int time){
            return releaseTime.contains(time);
        }
    }

    public static void main(String[] args) {
        RandomRelease release = new RandomRelease(0.3, 0.1);
        for(int i=4;i<18;i++){
            release.addTime(i);
        }
        release.generateRandomList();
    }
}
